//
//  HomeDetailViewController.m
//  location
//
//  Created by Dongxiang Xu on 2025/5/6.
//

#import "HomeDetailViewController.h"
#import "MemberDetailViewController.h"
#import "NotifyViewController.h"
#import "InviteView.h"
#import "HomeSheetPopView.h"
#import "ConfirmDeleteHomeView.h"
#import "UpdateHomeNameView.h"
#import "NowayExitVIew.h"
#import "UIImageView+WebCache.h"

@interface HomeDetailViewController ()

@property (nonatomic,strong) UIScrollView *scrollView;

@end

@implementation HomeDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = WhiteColor;

    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, NAVHEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT-NAVHEIGHT-110)];
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.alwaysBounceVertical = YES;
    if (@available(iOS 11.0, *)) {
        _scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    [self.view addSubview:_scrollView];
    
    [self getGroupInfo];
}

- (void)getGroupInfo
{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:_groupId forKey:@"groupId"];
    CryptoHTTPKit *manager = [[CryptoHTTPKit alloc] init];
    [manager encryptedPOST:@"/system/group/userinfo"
    parameters:param
    success:^(NSDictionary *responseObject) {
        if ([responseObject[@"code"] integerValue]==200 ) {
            [self initViewWithInfo:responseObject[@"data"]];
        }
    }
    failure:^(NSError *aError) {
       
    }];
}

- (void)initViewWithInfo:(NSDictionary *)info
{
    for (UIView *view in self.scrollView.subviews) {
        [view removeFromSuperview];
    }
    
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(16, 6, SCREEN_WIDTH-32, 32+(([info[@"groupInfo"][@"membership"] isKindOfClass:[NSDictionary class]])?20:0))];
    [self.scrollView addSubview:titleView];
    UITapGestureRecognizer *homeTap = [[UITapGestureRecognizer alloc] init];
    [[homeTap rac_gestureSignal] subscribeNext:^(id x) {
        HomeSheetPopView *view = [[HomeSheetPopView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) StartY:CGRectGetMaxY(titleView.frame)+6 TGroupId:self.groupId IsManage:NO];
        [self.tabBarController.view addSubview:view];
        
        view.RoomManageClickBlock = ^(NSDictionary *groupInfo) {
            self.groupId = groupInfo[@"id"];
            [self getGroupInfo];
        };
    }];
    [titleView addGestureRecognizer:homeTap];
    
//    UIButton *titleButton = [[UIButton alloc] initWithFrame:titleView.frame];
//    [self.scrollView addSubview:titleButton];
    
//    NSMutableArray *actionArray = [NSMutableArray array];
//
//    for (NSDictionary *groupInfo in self.groupList) {               
//        UIAction *action = [UIAction actionWithTitle:groupInfo[@"name"] image:nil identifier:nil handler:^(__kindof UIAction * _Nonnull action) {
//            self.groupId = groupInfo[@"id"];
//            [self getGroupInfo];
//        }];
//        
//        if ([groupInfo[@"membership"] isKindOfClass:[NSDictionary class]]) {
//            if ([groupInfo[@"membership"][@"planType"] integerValue]==3) {
//                action.subtitle = @"黄金会员";
//            }else if ([groupInfo[@"membership"][@"planType"] integerValue]==2){
//                action.subtitle = @"黄白银会员";
//            }else if ([groupInfo[@"membership"][@"planType"] integerValue]==1){
//                action.subtitle = @"亲密会员";
//            }
//        }
//        if ([groupInfo[@"id"] integerValue]==self.groupId.integerValue) {
//            action.state = UIMenuElementStateOn;
//        }
//        [actionArray addObject:action];
//    }
//    if (@available(iOS 14.0, *)) {
//        if (@available(iOS 15.0, *)) {
//            UIMenu *selectionGroup = [UIMenu menuWithTitle:@"" image:nil identifier:nil options:(UIMenuOptionsSingleSelection | UIMenuOptionsDisplayInline) children:actionArray];
//            titleButton.menu = [UIMenu menuWithTitle:@"" image:nil identifier:nil options:0 children:@[selectionGroup]];
//        }
//        titleButton.showsMenuAsPrimaryAction = YES;
//    }
    
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, titleView.width-32, 32)];
    title.textColor = RealBlackColor;
    title.font = REAL_MEDIUM_FONT(24);
    title.text = [NSString stringWithFormat:@"%@",info[@"groupInfo"][@"name"]];
    [titleView addSubview:title];
    
    UIImageView *titleImg = [[UIImageView alloc] initWithFrame:CGRectMake(titleView.width-16, 8, 16, 16)];
    titleImg.image = [UIImage imageNamed:@"home_exchange"];
    [titleView addSubview:titleImg];
    
    if ([info[@"groupInfo"][@"membership"] isKindOfClass:[NSDictionary class]]) {
        UIImageView *memberIcon = [[UIImageView alloc] initWithFrame:CGRectMake(0, title.maxY, 20, 20)];
        [titleView addSubview:memberIcon];
        
        UILabel *member = [[UILabel alloc] initWithFrame:CGRectMake(memberIcon.maxX+2, title.maxY, titleView.width-28, 20)];
        member.textColor = GraryTooHeavyColor;
        member.font = DEFAULT_FONT(12);
        [titleView addSubview:member];
        
        NSString *expireDate = [[[[info[@"groupInfo"][@"membership"][@"expireTime"] stringByReplacingCharactersInRange:NSMakeRange(4, 1) withString:@"年"] stringByReplacingCharactersInRange:NSMakeRange(7, 1) withString:@"月"] stringByReplacingCharactersInRange:NSMakeRange(10, 1) withString:@"日"] substringToIndex:11];
        
        if ([info[@"groupInfo"][@"membership"][@"planType"] integerValue]==1) {
            memberIcon.image = [UIImage imageNamed:@"icon_close"];
            member.text = [NSString stringWithFormat:@"%@会员 ｜ %@后到期",@"亲密",expireDate];
        }else if ([info[@"groupInfo"][@"membership"][@"planType"] integerValue]==2) {
            memberIcon.image = [UIImage imageNamed:@"icon_silver"];
            member.text = [NSString stringWithFormat:@"%@会员 ｜ %@后到期",@"白银",expireDate];
        }else if ([info[@"groupInfo"][@"membership"][@"planType"] integerValue]==3) {
            memberIcon.image = [UIImage imageNamed:@"icon_gold"];
            member.text = [NSString stringWithFormat:@"%@会员 ｜ %@后到期",@"黄金",expireDate];
        }
    }
    
    
    NSMutableArray *memberArray = [NSMutableArray array];
    if ([info[@"userInfo"] count]>0) {
        [memberArray addObjectsFromArray:info[@"userInfo"]];
    }
    
    UILabel *count = [[UILabel alloc] initWithFrame:CGRectMake(16, CGRectGetMaxY(titleView.frame)+16, SCREEN_WIDTH-32, 24)];
    count.textColor = GraryLightColor;
    count.font = REAL_MEDIUM_FONT(14);
    count.text = [NSString stringWithFormat:@"成员（%lu）",((NSArray *)info[@"userInfo"]).count];
    [self.scrollView addSubview:count];
            
    UIView *memberView = [[UIView alloc] initWithFrame:CGRectMake(16, CGRectGetMaxY(count.frame)+8, SCREEN_WIDTH-32, (memberArray.count+1)*66)];
    memberView.backgroundColor = RealWhiteColor;
    memberView.layer.masksToBounds = YES;
    [memberView.layer setCornerRadius:16];
    [self.scrollView addSubview:memberView];
       
    for (int i = 0; i < memberArray.count; i ++) {
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 66*i, memberView.width, 66)];
        [memberView addSubview:button];
        
        UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(16, (button.height-42)/2, 42, 42)];
        img.layer.masksToBounds = YES;
        [img.layer setCornerRadius:16];
        img.backgroundColor = GraryLightColor;
        [img sd_setImageWithURL:[NSURL URLWithString:memberArray[i][@"avatar"]]];
        [button addSubview:img];
        
        UILabel *name = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(img.frame)+12, 0, button.width-CGRectGetMaxX(img.frame)-94, button.height)];
        name.text = memberArray[i][@"remark"];
        name.font = MEDIUM_FONT(16);
        name.textColor = RealBlackColor;
        [button addSubview:name];
        
        UILabel *role = [[UILabel alloc] initWithFrame:CGRectMake(button.width-76, 0, 44, button.height)];
        if ([memberArray[i][@"userId"] integerValue] == [info[@"groupInfo"][@"adminId"] integerValue]) {
            role.text = @"管理员";
        }
        role.font = DEFAULT_FONT(14);
        role.textColor = GraryTooHeavyColor;
        [button addSubview:role];
        
        UIImageView *arrow = [[UIImageView alloc] initWithFrame:CGRectMake(button.width-28, (button.height-12)/2, 12, 12)];
        arrow.image = [UIImage imageNamed:@"arrow_right"];
        [button addSubview:arrow];
        
        UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(img.x, button.height-1, memberView.width-img.x*2, 1)];
        line.image = [UIImage imageNamed:@"line"];
        [button addSubview:line];
        
        [[button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            MemberDetailViewController *vc = [[MemberDetailViewController alloc] init];
            vc.adminId = info[@"groupInfo"][@"adminId"];
            NSMutableDictionary *info = [NSMutableDictionary dictionaryWithDictionary:memberArray[i]];
            [info setValue:self.groupId forKey:@"id"];
            vc.userInfo = info;
            vc.MemberDetailRemarkBlock = ^(NSString *remark) {
                name.text = remark;
            };
            vc.MemberDetailDeleteBlock = ^{
                for (UIView *view in self.scrollView.subviews) {
                    [view removeFromSuperview];
                }
                [self getGroupInfo];
            };
            [self.navigationController pushViewController:vc animated:YES];
        }];
    }
    
    UIButton *invite = [[UIButton alloc] initWithFrame:CGRectMake(0, 66*memberArray.count, memberView.width, 66)];
    [memberView addSubview:invite];
    [[invite rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {        
        InviteView *view = [[InviteView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) GroupInfo:info[@"groupInfo"]];
        [self.tabBarController.view addSubview:view];
    }];
    
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(16, (invite.height-42)/2, 42, 42)];
    imgView.layer.masksToBounds = YES;
    [imgView.layer setCornerRadius:16];
    imgView.backgroundColor = WhiteColor;
    [invite addSubview:imgView];
    
    UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake((imgView.width-24)/2, (imgView.height-24)/2, 24, 24)];
    img.image = [UIImage imageNamed:@"add_famliy"];
    [imgView addSubview:img];
    
    UILabel *name = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(imgView.frame)+12, 0, invite.width-CGRectGetMaxX(img.frame)-94, invite.height)];
    name.text = @"邀请成员";
    name.font = MEDIUM_FONT(16);
    name.textColor = RealBlackColor;
    [invite addSubview:name];
    
    UILabel *setting = [[UILabel alloc] initWithFrame:CGRectMake(16, CGRectGetMaxY(memberView.frame)+16, SCREEN_WIDTH-32, 24)];
    setting.textColor = GraryLightColor;
    setting.font = REAL_MEDIUM_FONT(14);
    setting.text = @"设置";
    [self.scrollView addSubview:setting];
    
    UIView *infoView = [[UIView alloc] initWithFrame:CGRectMake(16, CGRectGetMaxY(setting.frame)+8, SCREEN_WIDTH-32, 96)];
    infoView.backgroundColor = RealWhiteColor;
    infoView.layer.masksToBounds = YES;
    [infoView.layer setCornerRadius:16];
    [self.scrollView addSubview:infoView];
        
    [self loadInfoViewWithName:info[@"groupInfo"][@"name"] InfoView:infoView Info:info Title:title];
    [self.scrollView setContentSize:CGSizeMake(0, infoView.maxY+10)];

    
    UIButton *exit = [[UIButton alloc] initWithFrame:CGRectMake(16, SCREEN_HEIGHT-100, SCREEN_WIDTH-32, 60)];
    exit.backgroundColor = GraryHeavyLightColor;
    exit.layer.masksToBounds = YES;
    [exit.layer setCornerRadius:20];
    [exit setImage:[UIImage imageNamed:@"exit_home"] forState:UIControlStateNormal];
    [exit setTitle:@" 退出家庭" forState:UIControlStateNormal];
    [exit setTitleColor:RealWhiteColor forState:UIControlStateNormal];
    [exit.titleLabel setFont:REAL_MEDIUM_FONT(15)];
    exit.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [self.view addSubview:exit];
    [[exit rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        if ([info[@"groupInfo"][@"membership"] isKindOfClass:[NSDictionary class]] && [info[@"groupInfo"][@"memberCount"] integerValue]<=1) {
            NowayExitVIew *view = [[NowayExitVIew alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
            [self.view addSubview:view];
        }else{
            ConfirmDeleteHomeView *view = [[ConfirmDeleteHomeView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) GroupInfo:info IsAdmin:([info[@"groupInfo"][@"adminId"] integerValue] == [XDXShareInstance shareInstance].userId.integerValue)];
            view.ConfirmDeleteBlock = ^{
                [self.navigationController popViewControllerAnimated:YES];
                [XDXShareInstance shareInstance].ReloadGroupListFlag = YES;
                if (self.HomeDetailDeleteBlock) {
                    self.HomeDetailDeleteBlock(self.groupId);
                }
            };
            [self.view addSubview:view];
        }
    }];
}

- (void)loadInfoViewWithName:(NSString *)name InfoView:(UIView *)infoView Info:(NSDictionary *)info Title:(UILabel *)title
{
    for (UIView *view in infoView.subviews) {
        [view removeFromSuperview];
    }
    NSArray *infoArray = @[@"家庭名称",@"智能通知"];
    CGFloat y = 0;
    for (int i = 0; i < infoArray.count; i ++) {
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, y, infoView.width, 48)];
        button.tag = 50+i;
        [infoView addSubview:button];
                    
        if (i==0) {
            UILabel *role = [[UILabel alloc] initWithFrame:CGRectMake(92, 0, button.width-108-([info[@"groupInfo"][@"adminId"] integerValue]==[XDXShareInstance shareInstance].userId.integerValue?16:0), button.height)];
            role.textAlignment = NSTextAlignmentRight;
            role.text = [NSString stringWithFormat:@"%@",name];
            role.font = DEFAULT_FONT(14);
            role.textColor = GraryTooHeavyColor;
            role.numberOfLines = 0;
            [role sizeToFit];
            [button addSubview:role];
            [role setFrame:CGRectMake(infoView.width-role.width-16-([info[@"groupInfo"][@"adminId"] integerValue]==[XDXShareInstance shareInstance].userId.integerValue?16:0), 0, role.width, role.height+24)];
            if (role.height<48) {
                role.height = 48;
            }
            button.height = role.height;
            y = button.maxY;

            UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(16, button.height-1, infoView.width-32, 1)];
            line.image = [UIImage imageNamed:@"line"];
            [button addSubview:line];
            
            if ([info[@"groupInfo"][@"adminId"] integerValue]==[XDXShareInstance shareInstance].userId.integerValue) {
                UIImageView *arrow = [[UIImageView alloc] initWithFrame:CGRectMake(button.width-28, (button.height-12)/2, 12, 12)];
                arrow.image = [UIImage imageNamed:@"arrow_right"];
                [button addSubview:arrow];
                
                [[button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
                    UpdateHomeNameView *view = [[UpdateHomeNameView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) TGroupId:info[@"groupInfo"][@"id"] Name:info[@"groupInfo"][@"name"]];
                    view.UpdateHomeBlock = ^(NSString *name) {
                        [self loadInfoViewWithName:name InfoView:infoView Info:info Title:title];
                        title.text = name;
                    };
                    [self.view addSubview:view];
                }];
            }
        }else{
            UIImageView *arrow = [[UIImageView alloc] initWithFrame:CGRectMake(button.width-28, (button.height-12)/2, 12, 12)];
            arrow.image = [UIImage imageNamed:@"arrow_right"];
            [button addSubview:arrow];
            
            infoView.height = button.maxY;
            
            [[button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
                NotifyViewController *vc = [[NotifyViewController alloc] init];
                vc.groupInfo = @{@"id":self.groupId};
                [self.navigationController pushViewController:vc animated:YES];
            }];
            
        }
        
        UILabel *name = [[UILabel alloc] initWithFrame:CGRectMake(16, 0, 66, button.height)];
        name.text = infoArray[i];
        name.font = REAL_MEDIUM_FONT(16);
        name.textColor = RealBlackColor;
        [button addSubview:name];
    }
}

@end
